package com.qiaofang.applet.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义工具栏
 *
 * @author liangliang.luo
 */
@Slf4j
public class CustomUtil {
    private final static Map<String, String> FILE_TYPE_MAP = new HashMap<>();

    private CustomUtil() {
    }

    static {
        getAllFileType(); //初始化文件类型信息
    }

    private static void getAllFileType() {
        // images
        FILE_TYPE_MAP.put("FFD8FF", "jpg");
        FILE_TYPE_MAP.put("89504E47", "png");
        FILE_TYPE_MAP.put("47494638", "gif");
        FILE_TYPE_MAP.put("49492A00", "tif");
        FILE_TYPE_MAP.put("424D", "bmp");
        //
        FILE_TYPE_MAP.put("41433130", "dwg"); // CAD
        FILE_TYPE_MAP.put("38425053", "psd");
        FILE_TYPE_MAP.put("7B5C727466", "rtf"); // 日记本
        FILE_TYPE_MAP.put("3C3F786D6C", "xml");
        FILE_TYPE_MAP.put("68746D6C3E", "html");
        FILE_TYPE_MAP.put("44656C69766572792D646174653A", "eml"); // 邮件
        FILE_TYPE_MAP.put("D0CF11E0", "doc");
        FILE_TYPE_MAP.put("5374616E64617264204A", "mdb");
        FILE_TYPE_MAP.put("252150532D41646F6265", "ps");
        FILE_TYPE_MAP.put("255044462D312E", "pdf");
        FILE_TYPE_MAP.put("504B03040A00000000008", "docx");
        FILE_TYPE_MAP.put("504B0304", "zip");// zip 压缩文件
        FILE_TYPE_MAP.put("52617221", "rar");
        FILE_TYPE_MAP.put("57415645", "wav");
        FILE_TYPE_MAP.put("41564920", "avi");
        FILE_TYPE_MAP.put("2E524D46", "rm");
        FILE_TYPE_MAP.put("000001BA", "mpg");
        FILE_TYPE_MAP.put("000001B3", "mpg");
        FILE_TYPE_MAP.put("6D6F6F76", "mov");
        FILE_TYPE_MAP.put("3026B2758E66CF11", "asf");
        FILE_TYPE_MAP.put("4D546864", "mid");
        FILE_TYPE_MAP.put("1F8B08", "gz");
    }

    /**
     * 从HTML中提取图片链接
     */
    public static List<String> extractImg(String content) {
        List<String> srcList = new ArrayList<String>();
        if (StringUtils.isEmpty(content)) {
            return srcList;
        }
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if (hasPic == true) {
            while (hasPic) {
                String group = matcher.group(2);
                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher matcher2 = srcText.matcher(group);
                if (matcher2.find()) {
                    srcList.add(matcher2.group(3));
                }
                hasPic = matcher.find();
            }
        }
        return srcList;
    }

    /**
     * 清除html样式
     */
    public static String delHTMLTag(String htmlStr) {
        htmlStr = htmlStr.replaceAll("(<img\\b.*?(?:\\>|\\/>))", "[图片]");
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); //过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); //过滤html标签

        htmlStr = htmlStr.replace(" ", "");
        htmlStr = htmlStr.replaceAll("\\s*|\t|\r|\n", "");
        htmlStr = htmlStr.replace("“", "");
        htmlStr = htmlStr.replace("”", "");
        htmlStr = htmlStr.replaceAll("　", "");

        return htmlStr.trim(); //返回文本字符串
    }

    /**
     * 提取纯文字
     *
     * @param strHtml
     * @return
     */
    public static String StripHT(String strHtml) {
        if (StringUtils.isEmpty(strHtml)) {
            return "";
        }
//        strHtml = strHtml.replaceAll("(<img\\b.*?(?:\\>|\\/>))", "[图片]");
        String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); // 剔出<html>的标签
        txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");// 去除字符串中的空格,回车,换行符,制表符
        return txtcontent;
    }

    /**
     * 获取属性类型(type)，属性名(name)，属性值(value)的map组成的list
     *
     * @param o
     * @return
     */
    private static List getFiledsInfo(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        List list = new ArrayList();
        Map infoMap = null;
        for (int i = 0; i < fields.length; i++) {
            infoMap = new HashMap();
            infoMap.put("type", fields[i].getType().toString());
            infoMap.put("name", fields[i].getName());
            infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
            list.add(infoMap);
        }
        return list;
    }

    /**
     * 获取属性名数组
     *
     * @param o
     * @return
     */
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i].getType());
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param o
     * @return
     */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {

            return null;
        }
    }

    /**
     * 获取对象的所有属性值，返回一个对象数组
     *
     * @param o
     * @return
     */
    public static Object[] getFiledValues(Object o) {
        String[] fieldNames = getFiledName(o);
        Object[] value = new Object[fieldNames.length];
        for (int i = 0; i < fieldNames.length; i++) {
            value[i] = getFieldValueByName(fieldNames[i], o);
        }
        return value;
    }

    /**
     * 获取文件头
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == src || src.length < 1)
            return null;
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2)
                stringBuilder.append(0);
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据byte[]获取图片类型
     *
     * @param bytes
     * @return
     */
    public static String getFileType(byte[] bytes) {
        try {
            String fileCode = bytesToHexString(bytes).toLowerCase();
            if (fileCode.length() > 1)
                for (String key : FILE_TYPE_MAP.keySet())
                    if (fileCode.startsWith(key.toLowerCase()) || key.toLowerCase().startsWith(fileCode))
                        return FILE_TYPE_MAP.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据byte[]获取图片类型
     * @param inputStream
     * @return
     */
//    public static String getFileType(InputStream inputStream) {
//        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
//        try {
//            byte[] buff = new byte[1024];
//            int rc = 0;
//            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
//                swapStream.write(buff, 0, rc);
//            }
//            byte[] in2b = swapStream.toByteArray();
//            return getFileType(in2b);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 获取首字母
     */
    public static String getCharInitial(String str) {
        String charStr = "";
        if (StringUtils.isNotBlank(str)) {

        }
        return charStr;
    }


    /**
     * 替换指定标签的属性和值
     * @param str 需要处理的字符串
     * @param tag 标签名称
     * @param tagAttrib 要替换的标签属性值
     * @param startTag 新标签开始标记
     * @param endTag 新标签结束标记
     */
    public static String replaceHtmlTag(String str, String tag, String tagAttrib, String startTag, String endTag) {
        String regxpForTag = "<\\s*" + tag + "\\s+([^>]*)\\s*" ;
        String regxpForTagAttrib = tagAttrib + "=\\s*\"([^\"]+)\"" ;
        Pattern patternForTag = Pattern.compile (regxpForTag,Pattern. CASE_INSENSITIVE );
        Pattern patternForAttrib = Pattern.compile (regxpForTagAttrib,Pattern. CASE_INSENSITIVE );
        Matcher matcherForTag = patternForTag.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result = matcherForTag.find();
        while (result) {
            StringBuffer sbreplace = new StringBuffer( "<"+tag+" ");
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
            if (matcherForAttrib.find()) {
                String attributeStr = matcherForAttrib.group(1);
                //当查询到有域名时，不替换
                if(attributeStr.indexOf("http") < 0) {
                    matcherForAttrib.appendReplacement(sbreplace, startTag + attributeStr + endTag);
                }
            }
            matcherForAttrib.appendTail(sbreplace);
            matcherForTag.appendReplacement(sb, sbreplace.toString());
            result = matcherForTag.find();
        }
        matcherForTag.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        StringBuffer content = new StringBuffer();
        content.append("<ul class=\"imgBox\"><li><img id=\"160424\" data-src=\"uploads/allimg/160424/1-160424120T1-50.jpg\" src=\"uploads/allimg/160424/1-160424120T1-50.jpg\" class=\"src_class\"></li>");
        content.append("<li><img id=\"150628\" data-src=\"uploads/allimg/160424/1-160424120T1-50.jpg\" src=\"uploads/allimg/150628/1-15062Q12247.jpg\" class=\"src_class\"></li></ul>");
        System.out.println("原始字符串为:"+content.toString());
        String content1 = removeDataSrc(content.toString());
        System.out.println(content1);
        String newStr = replaceHtmlTag(content1.toString(), "img", "src", "src=\"http://junlenet.com/", "\"");
        System.out.println("  替换后为:"+newStr);
    }

    /**
     * 移除img标签中的data-src元素
     * @param content
     * @return
     */
    public static String removeDataSrc(String content) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if (hasPic == true) {
            while (hasPic) {
                String group = matcher.group(2);
                Pattern dataSrcText = Pattern.compile("(data-src)=(\"|\')(.*?)(\"|\')");
                Matcher matcher2 = dataSrcText.matcher(group);
                if (matcher2.find()) {
                    String data_src = matcher2.group(3);
                    if(StringUtils.isNotBlank(data_src)) {
                        String str = "data-src=\""+data_src+"\"";
                        content = content.replace(str, "");
                    }
                }
                hasPic = matcher.find();
            }
        }
        return replaceSrc(content);
    }

    private static String replaceSrc(String content) {
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if (hasPic == true) {
            while (hasPic) {
                String group = matcher.group(2);
                Pattern srcText = Pattern.compile("(src)=(\"|\')(.*?)(\"|\')");
                Matcher matcher2 = srcText.matcher(group);
                if (matcher2.find()) {
                    String src = matcher2.group(3);
                    if(StringUtils.isNotBlank(src)) {
                        if(src.indexOf("http") < 0) {

                        }
                        String img = "<img src=\"https://whwxadmin.qiaofangyun.com" + src + "\"/>";
                        String oldImg = "<img" + group +"\"/>";
                        content = content.replace(oldImg, img);
                    }
                }
                hasPic = matcher.find();
            }
        }
        return content;
    }
}
